<?php

namespace app\admin\controller;

use app\common\BaseAdminController;
use think\facade\Filesystem;
use think\facade\Db;
use app\model\Image as ImageModel;
use app\common\Result;

class Image extends BaseAdminController
{
    public function upload()
    {
        // 获取上传文件
        $file = request()->file('file');
        // 验证文件是否存在
        if (empty($file)) {
            return Result::error('请选择上传文件');
        }

        try {
            // 保存文件到public/uploads目录
            $saveName = str_replace('\\', '/', Filesystem::disk('public')->putFile('uploads', $file));
            // 获取完整的HTTP访问路径
            $url = request()->domain() . "/" . $saveName;

            $image = new ImageModel();
            $image->image = $url;

            $result = $image->save();

            if ($result === false) {
                return Result::error('保存文件信息失败');
            } else {
                return Result::success(['url' => $url, 'id' => $image->id], '上传成功');
            }
        } catch (\Exception $e) {
            return Result::error('上传失败: ' . $e->getMessage());
        }
    }

    public function list($pageNum = 1, $pageSize = 10)
    {
        // 初始化查询构建器
        $query = Db::table('image')
            ->order('id', 'desc')
            ->page($pageNum, $pageSize);
        // 获取查询结果
        $list = $query->select();
        // 获取总记录数
        $total = $query->count();
        // 返回包含查询结果和总记录数的 JSON 数据
        return Result::success(['list' => $list, 'total' => $total], '查询成功');
    }
}
